<?php

namespace App\Console\Commands\Test;

use BigBoom\Zookeeper\Facades\Zk;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'just for test';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->removeAllZookeeperNode('');
//        $this->testLock();
    }

    public function testLock()
    {
        $lockKey = Zk::lock("lock", 100);
        dd($lockKey);
    }

    public function removeAllZookeeperNode($node)
    {
        /* $value = Zk::get('/test');
         dd($value);*/

        $children = Zk::getChildren($node === "" ? '/' : $node);
        if ($children) {
            foreach ($children as $path) {
                if ($node . '/' . $path === '/zookeeper') {
                    continue;
                }
                $this->removeAllZookeeperNode($node . '/' . $path);
            }

            if ($node !== '/zookeeper' && $node !== '') {
                Zk::remove($node);
            }
        } else {
            Zk::remove($node);
            $this->info("remove " . $node);
        }
    }

    public function testLogWrite()
    {
        $level = ['info', 'warning', 'error'];
        $max = 1000;
        for ($i = 0; $i < $max; $i++) {
            Log::{$level[random_int(0, 2)]}(Str::random(32));
        }
    }

    protected function testHashAlgosPerformance()
    {
        $str = bin2hex(random_bytes(1000));

        $hashWasteTimes = [];

        foreach (hash_algos() as $algo) {
            $start = microtime(true);
            for ($i = 0; $i < 10000; $i++) {
                hash($algo, $str);
            }
            $end = microtime(true);
            $wasteTime = number_format($end - $start, 10, '.', '');
            $hashWasteTimes[$algo] = $wasteTime;
        }

        asort($hashWasteTimes);

        dd($hashWasteTimes);
    }
}
